<!--{template common/header}-->
<style>
    .er-kami-header {
        margin: 12px auto;
        padding: 0 20px;
        text-align: center;
    }
    .er-kami-header h2 {
        font-size: 24px;
        font-weight: 600;
        color: #2c3e50;
        margin: 0;
        padding: 10px 0;
        position: relative;
        display: inline-block;
    }
    .er-kami-header h2:after {
        content: '';
        position: absolute;
        width: 50%;
        height: 3px;
        background: #3498db;
        bottom: 0;
        left: 25%;
        border-radius: 3px;
    }
    .er_kami_exchange {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
        gap: 20px;
        padding: 20px;
    }

    .er_kami_type {
        display: flex;
        flex-direction: column;
        border: 1px solid #e5e5e5;
        border-radius: 8px;
        padding: 15px;
        background: #fff;
        box-shadow: 0 2px 5px rgba(0,0,0,0.1);
    }

    .er_kami_type_name {
        font-size: 18px;
        font-weight: bold;
        margin-bottom: 10px;
        color: #333;
    }

    .er_kami_type_desc {
        font-size: 14px;
        color: #666;
        margin-bottom: 10px;
        flex-grow: 1;
    }

    .er_kami_type_credit {
        font-size: 16px;
        color: #e74c3c;
    }

    .er_kami_type_exchange {
        margin-top: 10px;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .exchange-btn {
        background: #3498db;
        color: white;
        border: none;
        padding: 8px 20px;
        border-radius: 4px;
        cursor: pointer;
        transition: background 0.3s;
    }

    .exchange-btn:hover {
        background: #2980b9;
    }

    .exchange-btn-before {
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 80%;
        max-width: 500px;
        background: #fff;
        border-radius: 8px;
        padding: 20px;
        box-shadow: 1px 0 20px 6px rgb(77 77 77 / 44%);
        z-index: 5;
    }

    .exchange-btn-before h2 {
        font-size: 20px;
        margin-bottom: 15px;
        color: #333;
        border-bottom: 1px solid #eee;
        padding-bottom: 10px;
    }

    .exchange-btn-before p {
        margin: 10px 0;
        font-size: 16px;
    }

    .exchange-btn-before h3 {
        font-size: 16px;
        margin: 15px 0 10px;
        color: #e74c3c;
    }

    .exchange-btn-before > div {
        margin-bottom: 15px;
    }

    .exchange-btn-before button {
        padding: 8px 20px;
        border-radius: 4px;
        cursor: pointer;
        margin-right: 10px;
    }

    .exchange-btn-before button:last-child {
        background: #3498db;
        color: white;
        border: none;
    }

    .exchange-btn-before button:last-child:hover {
        background: #2980b9;
    }
    .exchange-btn-after {
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 80%;
        max-width: 500px;
        background: #fff;
        border-radius: 8px;
        padding: 20px;
        box-shadow: 1px 0 20px 6px rgb(77 77 77 / 44%);
        z-index: 5;
        text-align: center;
    }
    
    .exchange-btn-after h2 {
        color: #4CAF50;
        font-size: 24px;
        margin-bottom: 15px;
    }
    
    .exchange-btn-after-content {
        margin: 15px 0;
        font-size: 16px;
    }
    
    .exchange-btn-after-item {
        margin-bottom: 10px;
    }
    
    .kami-key {
        font-weight: bold;
        color: #2196F3;
        word-break: break-all;
    }
    
    .copy-kami-btn {
        background: #4CAF50;
        color: white;
        border: none;
        padding: 8px 20px;
        border-radius: 4px;
        cursor: pointer;
        margin-bottom: 15px;
    }
    
    .close-success-btn {
        background: #f44336;
        color: white;
        border: none;
        padding: 8px 20px;
        border-radius: 4px;
        cursor: pointer;
    }
    .exchange-btn-after-error {
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 80%;
        max-width: 500px;
        background: #fff;
        border-radius: 8px;
        padding: 20px;
        box-shadow: 1px 0 20px 6px rgb(77 77 77 / 44%);
        z-index: 5;
        text-align: center;
    }
    
    .exchange-btn-after-error h2 {
        color: #f44336;
        font-size: 24px;
        margin-bottom: 15px;
    }
    
    .kami-type-error {
        color: #f44336;
        word-break: break-all;
    }

    .er-kami-header-b {
        display: flex;
        justify-content: space-between;
        background-color: #d7ecff;
        padding: 10px;
    }
    .er-kami-header-right, .er-kami-header-right a{
        color: #666;
    }
</style>
<div class="er-kami-header">
    <h2>{$er_kami_buy_config['nav_name']['value']}</h2>
    <div class="er-kami-header-b">
        <div class="er-kami-header-left">
            {loop $credits $key $credit}
                {if $credit['title']}
                    <span class="er-kami-header-left-title">{$credit['title']}: {$credit['value']}</span> | 
                {/if}
            {/loop}

            
            <span><a href="{$er_kami_buy_config['recharge_url']['value']}" style="text-decoration: underline;">充值积分</a></span>
             | 
            <span><a href="home.php?mod=spacecp&ac=plugin&id=erling_kami_buy:user_kami" style="text-decoration: underline;">我的卡密</a></span>
        </div>
        <div class="er-kami-header-right">
            <span class="er-copyright">© 20idc.com</span>
        </div>
    </div>
</div>

<div class="er_kami_exchange" id="er_kami_exchange">
    {loop $table_er_kami_buy_type_list $kami_buy_type}
    <div class="er_kami_type">
        <div class="er_kami_type_name">
            {$kami_buy_type['name']}
        </div>
        <div class="er_kami_type_desc">
            {$kami_buy_type['desc']}
        </div>
        <div>
            剩余卡密：{$kami_buy_type['kami_count']}
        </div>
        <div class="er_kami_type_exchange">
            <div class="er_kami_type_credit">
                {$extcredits_data[$kami_buy_type['extcredits']]['title']}：{$kami_buy_type['credit']}
            </div>
            <button class="exchange-btn" onclick="showConfirmDialog('{$kami_buy_type['id']}', '{$kami_buy_type['name']}', '{$kami_buy_type['desc']}', '{$extcredits_data[$kami_buy_type['extcredits']]['title']}：{$kami_buy_type['credit']}', '{$credits['extcredits'.$kami_buy_type['extcredits']]['value']}')">购买卡密</button>
        </div>
    </div>
    {/loop}
</div>

<div class="exchange-btn-before" style="display:none;">
    <input hidden type="number" value="" id="kami_buy_type_id">
    <input hidden type="text" value="" id="er_api">
    <h2>您正在兑换卡密：<span id="kamiTypeName"></span></h2>
    <div id="kamiTypeDesc"></div>
    <div>
        <p>需扣除 <span id="kamiTypeCredit"></span></p>
        <p>您当前余额：<span id="userCredit"></span></p>
    </div>
    <div>
        <h3>兑换注意事项：</h3>
        <div>{$er_kami_buy_config['precautions']['value']}</div>
    </div>
    <div>
        <button onclick="hideConfirmDialog()">取消</button>
        <button onclick="doExchangeKami()">确认兑换</button>
    </div>
</div>

<div class="exchange-btn-after" style="display:none;">
    <h2>兑换成功！</h2>
    <div class="exchange-btn-after-content">
        <div class="exchange-btn-after-item">卡密类型：<span id="er_kamiTypeName" class="kami-type-name"></span></div>
        <div class="exchange-btn-after-item">卡密：<span id="er_kamiKey" class="kami-key"></span></div>
    </div>
    <button onclick="copyKamiKey()" class="copy-kami-btn">点击复制卡密</button>
    <div>
        <a href="home.php?mod=spacecp&ac=plugin&id=erling_kami_buy:user_kami" target="_blank" style="text-decoration: underline;">我的卡密</a>
        <button onclick="hideSuccessDialog()" class="close-success-btn">关闭</button>
    </div>
</div>

<div class="exchange-btn-after-error" style="display:none;">
    <h2>兑换失败！</h2>
    <div class="exchange-btn-after-content">
        <div class="exchange-btn-after-item">错误信息：<span id="kamiTypeError" class="kami-type-error"></span></div>
    </div>
    <div>
        <button onclick="hideErrorDialog()" class="close-success-btn">关闭</button>
    </div>
</div>


<script>
    function exchangeKami(kamiTypeId,er_api) {
        var formhash = '{FORMHASH}';

        var url_page = 'plugin.php?id=erling_kami_buy:user_kami_exchange&buy_kami=1';
        
        // 显示加载状态
        var btn = event.target;
        var originalText = btn.innerHTML;
        btn.innerHTML = '处理中...';
        btn.disabled = true;
        
        // 创建 FormData 对象
        var formData = new FormData();
        formData.append('formhash', formhash);
        formData.append('kami_type', kamiTypeId);
        formData.append('er_api', er_api);
        
        // 发送 AJAX 请求
        var xhr = new XMLHttpRequest();
        xhr.open('POST', url_page, true);
        xhr.onload = function() {
            btn.innerHTML = originalText;
            btn.disabled = false;
            
            if (xhr.status === 200) {
                try {
                    var response = JSON.parse(xhr.responseText);
                    if (response.success) {
                        console.log(response);
                        // 显示成功弹窗
                        document.getElementById('er_kamiTypeName').textContent = response.kami_buy_type;
                        document.getElementById('er_kamiKey').textContent = response.kami_key;
                        document.querySelector('.exchange-btn-after').style.display = 'block';
                        document.querySelector('.exchange-btn-before').style.display = 'none';
                    } else {
                        document.getElementById('kamiTypeError').textContent = response.message || '未知错误';
                        document.querySelector('.exchange-btn-after-error').style.display = 'block';
                        document.querySelector('.exchange-btn-before').style.display = 'none';
                    }
                } catch (e) {
                    document.getElementById('kamiTypeError').textContent = '解析响应数据失败';
                    document.querySelector('.exchange-btn-after-error').style.display = 'block';
                }
            } else {
                document.getElementById('kamiTypeError').textContent = '请求失败，状态码：' + xhr.status;
                document.querySelector('.exchange-btn-after-error').style.display = 'block';
            }
        };
        xhr.onerror = function() {
            btn.innerHTML = originalText;
            btn.disabled = false;
            alert('网络请求错误');
        };
        xhr.send(formData);
        
    }


    function showConfirmDialog(kamiTypeId, name, desc, credit, userCredit,er_api='') {
        document.getElementById('kami_buy_type_id').value = kamiTypeId;
        document.getElementById('er_api').value = er_api;
        document.getElementById('kamiTypeName').innerText = name;
        document.getElementById('kamiTypeDesc').innerText = desc;
        document.getElementById('kamiTypeCredit').innerText = credit;
        document.getElementById('userCredit').innerText = userCredit;
        document.querySelector('.exchange-btn-before').style.display = 'block';
    }
    
    function hideConfirmDialog() {
        document.querySelector('.exchange-btn-before').style.display = 'none';
    }
    
    function doExchangeKami() {
        var kamiTypeId = document.getElementById('kami_buy_type_id').value;
        var er_api = document.getElementById('er_api').value;
        exchangeKami(kamiTypeId,er_api);
        hideConfirmDialog();
    }

    function copyKamiKey() {
        var kamiKey = document.getElementById('er_kamiKey').textContent;
        if (navigator.clipboard) {
            navigator.clipboard.writeText(kamiKey).then(function() {
                showDialog('卡密已复制到剪贴板', 'notice', null, null, 0, null, null, null, null, 2);
            }).catch(function() {
                fallbackCopy(kamiKey);
            });
        } else {
            fallbackCopy(kamiKey);
        }
    }

    function fallbackCopy(text) {
        var textarea = document.createElement('textarea');
        textarea.value = text;
        textarea.style.position = 'fixed';
        document.body.appendChild(textarea);
        textarea.select();
        
        try {
            var successful = document.execCommand('copy');
            if (successful) {
                showDialog('卡密已复制到剪贴板', 'notice', null, null, 0, null, null, null, null, 2);
            } else {
                showDialog('复制失败！请手动复制', 'notice', null, null, 0, null, null, null, null, 2);
            }
        } catch (err) {
            showDialog('复制失败！请手动复制', 'notice', null, null, 0, null, null, null, null, 2);
        }
        
        document.body.removeChild(textarea);
    }

    function hideSuccessDialog() {
        document.querySelector('.exchange-btn-after').style.display = 'none';
        location.reload();
    }
    function hideErrorDialog() {
        document.querySelector('.exchange-btn-after-error').style.display = 'none';
    }


    function getKamiFromAPI() {
        var api = '{$er_kami_buy_config["kami_api"]["value"]}';
        if(api == 1){
            var apiUrl = '{$er_kami_buy_config["kami_api_url"]["value"]}';
            if(!apiUrl) {
                return;
            }
            fetch(apiUrl).then(response => response.json()).then(data => {
                
                let creditRules = '{$er_kami_buy_config["kami_api_site_credit"]["value"]}';
                creditRules = JSON.parse(creditRules);
                function findCreditRuleById(id) {
                    return creditRules.find(rule => rule.id == id);
                }
                console.log(data);
                console.log(creditRules);
                const extcredits_data = '{$extcredits_data_json}';
                const extcredits_data_array = JSON.parse(extcredits_data);

                const exchangeDiv = document.getElementById('er_kami_exchange');
                data.data.forEach(item => {
                    const typeDiv = document.createElement('div');
                    const rule = findCreditRuleById(item.id);

                    typeDiv.className = 'er_kami_type';
                    
                    typeDiv.innerHTML = `
                        <div class="er_kami_type_name">${item.name}</div>
                        <div class="er_kami_type_desc">${item.description??''}</div>
                        <div>剩余卡密：${item.kami_keys_count}</div>
                        <div class="er_kami_type_exchange">
                            <div class="er_kami_type_credit">${extcredits_data_array[rule.extcredits].title}：${rule.credit}</div>
                            <button class="exchange-btn" onclick="showConfirmDialog(${item.id},'${item.name}','${item.description??''}','${extcredits_data_array[rule.extcredits].title}：${rule.credit}','','api')">购买卡密</button>
                        </div>
                    `;
                    
                    exchangeDiv.appendChild(typeDiv);
                });
            })
            .catch(error => {
                console.error('Error fetching data:', error);
            });
        }
    }

    getKamiFromAPI();
</script>
<script src="https://t.9py.cn/c/copyright.js"></script>
<!--{template common/footer}-->